package com.hllxd.hism.passport.login.gateway.dao.http;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;

/**
 * 添加新
 * @author xiyong.lxy
 * @date 2018/5/5.
 */
@Slf4j
public class OkHttpUtil {

    public final static int CONNECT_TIMEOUT = 3;
    // 10min
    public final static int READ_TIMEOUT = 600;
    public final static int WRITE_TIMEOUT = 60;
    //@Bean
    public static OkHttpClient okHttpClient() {
        return new OkHttpClient.Builder()
            //.sslSocketFactory(sslSocketFactory(), x509TrustManager())
            .retryOnConnectionFailure(false)
                    //连接超时
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                    //读超时
            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                    //写超时
            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
            .build();
    }

    public static String postJsonParams(String url, String jsonParams) throws Exception {
        OkHttpClient okHttpClient = okHttpClient();

        String responseBody = "";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                ResponseBody responseBody1 = response.body();
                if(responseBody1!=null) {
                    return responseBody1.string();
                }
                return null;
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }
    public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
    public static String httpGet(String url) throws IOException {
        //OkHttpClient httpClient = new OkHttpClient();
        OkHttpClient httpClient = okHttpClient();
        Request request = new Request.Builder()
            .url(url)
            .build();
        Response response = null;
        try{
            response = httpClient.newCall(request).execute();
            ResponseBody body = response.body();
            if(body==null) {
                return null;
            }
            // 返回的是string 类型，json的mapper可以直接处理
            return body.string();
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

    public static String httpPost(String json, String url) throws IOException {
        return httpPost(json, url, 0);
    }
    private static String httpPost(String json, String url,int retry) throws IOException {
        //OkHttpClient httpClient = new OkHttpClient();
        OkHttpClient httpClient = okHttpClient();
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
        Response response = null;
        try{
            response = httpClient.newCall(request).execute();
            ResponseBody body = response.body();
            if(body==null) {
                return null;
            }
            return body.string();
        } catch (SocketTimeoutException e) {
            log.warn("http request will retry {}. ", retry, e.getCause());
            httpClient.dispatcher().cancelAll();
            httpClient.connectionPool().evictAll();
            if(retry>7) {
                log.warn("httpPost timeout retry:{}, url: {}, json: {}",retry, url, json);
                return null;
            }
            return httpPost(json,url, ++retry);
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

    public static JSONObject ajaxPost(String json, String uri) {
        String responseResult;
        try {
            responseResult = OkHttpUtil.httpPost(json, uri);
        }
        catch (Exception e){
            log.error("exception: {}.",e.toString());
            return null;
        }
        try {
            JSONObject jsonObject = com.alibaba.fastjson.JSON.parseObject(responseResult);
            String traceID = jsonObject.getString("traceID");
            String status = jsonObject.getString("success");
            Long ms = jsonObject.getLong("ms");
//            if(status!=null&&! status.equals("true")) {
//                log.warn("[{}] request failed. msg: {}, processMs: {}.",traceID, responseResult,ms);
//                return null;
//            }
            log.info("[{}] request status: {}, ms: {}, result: {}.", traceID, status, ms, responseResult);
            return jsonObject;
        }catch (Exception e) {
            log.warn("Exception: {}",e.toString());
        }
        return null;
    }


    public static boolean isSuccess(JSONObject obj) {
        String status = obj.getString("success");
        String TRUE_CODE = "true";
        return (status!=null && status.equals(TRUE_CODE));
    }
}
